package com.donger.business.upms.utils;

import com.alipay.api.internal.util.codec.Base64;
import lombok.SneakyThrows;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author 7326
 */
public class DingUtils {


    @SneakyThrows
    public static String getSignature(String appSecret, String timestamp){
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signatureBytes = mac.doFinal(timestamp.getBytes(StandardCharsets.UTF_8));
        String signature = new String(Base64.encodeBase64(signatureBytes));

        return urlEncode(signature,"utf-8");

    }

    /**
     *     encoding参数使用utf-8
      */
    @SneakyThrows
    public static String urlEncode(String value, String encoding) {
        if (value == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(value, encoding);
            return encoded.replace("+", "%20").replace("*", "%2A")
                    .replace("~", "%7E").replace("/", "%2F");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("FailedToEncodeUri", e);
        }
    }
}
